(Quick Reference)

withUser(identity, Closure code)

Available in Controllers, Domains, Taglibs and Services

This method executes a block of code masquerading as another user. Used mainly to create fixtures or perform background tasks.

The implementation of this method is provided by the security provider you have installed.

Usage

class PurchaseService {
    void updatePurchasesForUser(String userName) {
        withUser(userName) {
            Purchase.findAllByUser(securityInfo).each { p ->
                p.updateStatus()
            }
        }
    }
    …
}

In this example you can see that the securityInfo is set according to the identity of the user passed to withUser.

Arguments

NameDescription
identityThe user identity - usually a username or email address, but it depends on your security provider
codeThe Closure of code to run "as" the user